import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';
import { useDispatch } from 'react-redux';
import { useEffect, useRef, useState } from 'react';
import {
  clearResultActionCreator,
  getResultActionCreator,
} from '@/store/action/search';
import { useAppSelector } from '@/store';
import history from '@/utils/history';
import { InfiniteScroll } from 'antd-mobile';

export default function SearchResult() {
  const dispatch = useDispatch();

  // 跳转到文章详情页
  const gotoArticleDetail = (articleId: string) => {
    console.log(1);
    history.push(`/article/${articleId}`);
  };

  // 获取搜搜结果并渲染
  const { searchResults } = useAppSelector((state) => state.search);
  console.log(25, searchResults);

  // 获取从搜搜页面传入的查询参数
  const { search } = useLocation();
  // console.log(10, search);

  // MDN文档：https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams
  const searchParams = new URLSearchParams(search);
  // console.log(14, searchParams);

  // 获取 URL 的查询参数 q 的值
  const q = searchParams.get('q') || '';

  console.log('获取查询参数q的值', q);

  // 获取搜索结果(交给无限加载组件发送请求就行，这里不用了)
  useEffect(() => {
    dispatch(getResultActionCreator({ q }));
  }, [q, dispatch]);

  // 是否还有更多内容

  // 页码
  const page = useRef(0);
  // 加载更多回调函数
  const loadMoreFn = async () => {
    // 页码加一
    page.current = page.current + 1;
    await dispatch(
      getResultActionCreator({ q: q, page: page.current, per_page: 10 })
    );
  };

  // 定义计算属性，计算hasMore是否为true
  // page * 10 代表理论上请求回来的总数，如果实际数量小于理论数量，代表数据已经被查光了
  const hasMore = page.current * 10 <= searchResults.length;

  // 组件卸载时，清理数据
  useEffect(() => {
    dispatch(clearResultActionCreator());
  }, [dispatch]);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {searchResults.map((item) => (
          <ArticleItem
            key={item.art_id}
            article={item}
            onClick={() => gotoArticleDetail(item.art_id)}
          />
        ))}
      </div>
      <InfiniteScroll loadMore={loadMoreFn} hasMore={hasMore} />
    </div>
  );
}
